package com.jbinfo.common.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 
 * @ClassName: JSONUtils
 * @Description: TODO 工具类
 * @author zhanglei
 * @date 2014-11-20 下午5:16:13
 */
public class JSONUtils {
	/**
	 * Logger for this class
	 */
	private static final Logger LOGGER = Logger.getLogger(JSONUtils.class);

	/**
	 * 
	 * @Title: toArrayList
	 * @Description: TODO 将对象转换为List对象
	 * @author zhanglei
	 * @date 2014-11-20 下午5:08:18
	 * @param @param object
	 * @param @return 设定文件
	 * @return List 返回类型
	 * @throws
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static List toArrayList(Object object) {
		List arrayList = new ArrayList();
		JSONArray jsonArray = JSONArray.fromObject(object);
		Iterator it = jsonArray.iterator();
		while (it.hasNext()) {
			JSONObject jsonObject = (JSONObject) it.next();
			Iterator keys = jsonObject.keys();
			while (keys.hasNext()) {
				Object key = keys.next();
				Object value = jsonObject.get(key);
				arrayList.add(value);
			}
		}
		return arrayList;
	}

	/**
	 * 
	 * @Title: toJSONObject
	 * @Description: TODO 将对象转换为JSON对象
	 * @author zhanglei
	 * @date 2014-11-20 下午5:07:50
	 * @param @param object
	 * @param @return 设定文件
	 * @return JSONObject 返回类型
	 * @throws
	 */
	public static JSONObject toJSONObject(Object object) {
		return JSONObject.fromObject(object);
	}

	/**
	 * 
	 * @Title: toHashMap
	 * @Description: TODO 将对象转换为HashMap
	 * @author zhanglei
	 * @date 2014-11-20 下午5:07:31
	 * @param @param object
	 * @param @return 设定文件
	 * @return HashMap 返回类型
	 * @throws
	 */
	@SuppressWarnings("rawtypes")
	public static HashMap toHashMap(Object object) {
		HashMap<String, Object> data = new HashMap<String, Object>();
		JSONObject jsonObject = JSONUtils.toJSONObject(object);
		Iterator it = jsonObject.keys();
		while (it.hasNext()) {
			String key = String.valueOf(it.next());
			Object value = jsonObject.get(key);
			data.put(key, value);
		}
		return data;
	}

	/**
	 * 
	 * @Title: toList
	 * @Description: TODO 将对象转换为List<Map<String,Object>>
	 * @author zhanglei
	 * @date 2014-11-20 下午5:07:17
	 * @param @param object
	 * @param @return 设定文件
	 * @return List<Map<String,Object>> 返回类型
	 * @throws
	 */
	@SuppressWarnings("rawtypes")
	public static List<Map<String, Object>> toList(Object object) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		JSONArray jsonArray = JSONArray.fromObject(object);
		for (Object obj : jsonArray) {
			JSONObject jsonObject = (JSONObject) obj;
			Map<String, Object> map = new HashMap<String, Object>();
			Iterator it = jsonObject.keys();
			while (it.hasNext()) {
				String key = (String) it.next();
				Object value = jsonObject.get(key);
				map.put((String) key, value);
			}
			list.add(map);
		}
		return list;
	}

	/**
	 * 
	 * @Title: toList
	 * @Description: TODO 将对象转换为传入类型的List
	 * @author zhanglei
	 * @date 2014-11-20 下午5:06:24
	 * @param @param object
	 * @param @param objectClass
	 * @param @return 设定文件
	 * @return List<T> 返回类型
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	public static <T> List<T> toList(Object object, Class<T> objectClass) {
		JSONArray jsonArray = JSONArray.fromObject(object);
		return JSONArray.toList(jsonArray, objectClass);
	}

	/**
	 * 
	 * @Title: toBean
	 * @Description: TODO 将将对象转换为传入类型的对象
	 * @author zhanglei
	 * @date 2014-11-20 下午5:05:13
	 * @param @param object
	 * @param @param beanClass
	 * @param @return 设定文件
	 * @return T 返回类型
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	public static <T> T toBean(Object object, Class<T> beanClass) {
		JSONObject jsonObject = JSONObject.fromObject(object);
		return (T) JSONObject.toBean(jsonObject, beanClass);
	}

	/**
	 * 
	 * @Title: aoDataToModel
	 * @Description: TODO DataTables页码参数封装到应对的model
	 * @author zhanglei
	 * @date 2014-11-20 下午5:05:31
	 * @param @param aoData
	 * @param @param modelClass
	 * @param @return 设定文件
	 * @return T 返回类型
	 * @throws
	 */
	public static <T> T aoDataToModel(String aoData, Class<T> modelClass) {

		HashMap<String, String> map = JSONUtils.convertStringToMap(aoData);

		JSONObject jsObjectModel = JSONUtils.getJsonObject4Class(map, modelClass);
		T model = JSONUtils.toBean(jsObjectModel, modelClass);

		JSONObject jsObjectTables = JSONUtils.getJsonObject4Class(map, DataTables.class);
		DataTables<?> dataTables = JSONUtils.toBean(jsObjectTables, DataTables.class);

		try {
			BeanUtils.setProperty(model, "dataTables", dataTables);
		} catch (IllegalAccessException e) {
			LOGGER.info(e.getMessage());
		} catch (InvocationTargetException e) {
			LOGGER.info(e.getMessage());
		}
		return model;
	}

	/**
	 * 
	 * @Title: convertStringToMap
	 * @Description: TODO 将DataTables页码参数封装为HashMap
	 * @author zhanglei
	 * @date 2014-11-21 上午10:45:00
	 * @param @param aoData
	 * @param @return 设定文件
	 * @return HashMap<String,String> 返回类型
	 * @throws
	 */
	public static HashMap<String, String> convertStringToMap(String aoData) {
		org.json.JSONArray jsonArray = new org.json.JSONArray(aoData);
		HashMap<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < jsonArray.length(); i++) // 从传递参数里面选出待用的参数
		{
			org.json.JSONObject obj = (org.json.JSONObject) jsonArray.get(i);
			map.put(obj.get("name").toString(), obj.get("value").toString());
		}
		return map;
	}

	/**
	 * 
	 * @Title: getJsonObject4Class
	 * @Description: TODO 根据bean中的属性过滤map 返回 JSONObject
	 * @author zhanglei
	 * @date 2014-11-21 上午10:45:14
	 * @param @param map
	 * @param @param modelClass
	 * @param @return 设定文件
	 * @return JSONObject 返回类型
	 * @throws
	 */
	@SuppressWarnings("rawtypes")
	public static <T> JSONObject getJsonObject4Class(HashMap map, Class<T> modelClass) {
		HashMap<String, String> resultMap = new HashMap<String, String>();
		List<String> modeList = new ArrayList<String>();

		Field[] fields = modelClass.getDeclaredFields();// 得到对象中的字段
		for (int i = 0; i < fields.length; i++) {
			Field field = fields[i];
			String fieldName = field.getName();
			modeList.add(fieldName);
		}

		Iterator<Entry<String, String>> entryKeyIterator = map.entrySet().iterator();
		while (entryKeyIterator.hasNext()) {
			Entry<String, String> e = entryKeyIterator.next();
			String key = e.getKey();
			String value = e.getValue();
			if (modeList.contains(key)) {
				resultMap.put(key, value);
			}
		}

//		Iterator it = map.keySet().iterator();
//		while (it.hasNext()) {
//			String key = (String) it.next();
//			String value = (String) map.get(key);
//			if (modeList.contains(key)) {
//				resultMap.put(key, value);
//			}
//		}

		return JSONUtils.toJSONObject(resultMap);
	}

	/**
	 * 
	 * @Title: aoDataToModelByReflect
	 * @Description: TODO 反射方式
	 * @author zhanglei
	 * @date 2014-12-3 上午9:09:26
	 * @param @param aoData
	 * @param @param modelClass
	 * @param @return 设定文件
	 * @return T 返回类型
	 * @throws
	 */
//	public static <T> T aoDataToModelByReflect(String aoData, T modelClass) {
//
//		HashMap<String, String> map = JSONUtils.convertStringToMap(aoData);
//
//		T model = JSONUtils.convertHashMap2Bean(map, modelClass);
//
//		DataTables<?> dataTables = JSONUtils.convertHashMap2Bean(map, new DataTables());
//
//		try {
//			BeanUtils.setProperty(model, "dataTables", dataTables);
//		} catch (IllegalAccessException e) {
//			LOGGER.info(e.getMessage());
//		} catch (InvocationTargetException e) {
//			LOGGER.info(e.getMessage());
//		}
//		return model;
//	}

	/**
	 * 
	 * @Description:TODO
	 * @param map
	 * @param modelBean
	 * @return
	 * @return T
	 * @exception:
	 * @author:
	 * @time:2014-12-18 上午9:48:47
	 */
//	@SuppressWarnings("rawtypes")
//	public static <T> T convertHashMap2Bean(HashMap<?, ?> map, T modelBean) {
//		// 封装属性
//		Map<String, Field> fieldMap = new HashMap<String, Field>();
//		// 封装属性的set方法
//		Map<String, Method> methodMap = new HashMap<String, Method>();
//		Class<?> classType = modelBean.getClass();
//		Iterator it = map.keySet().iterator();
//		try {
//			Field[] fields = classType.getDeclaredFields();// 得到对象中的字段
//			Method[] methods = classType.getDeclaredMethods();
//
//			for (Field field : fields) {
//				String attri = field.getName();
//				fieldMap.put(attri.toLowerCase(), field);
//
//				for (Method method : methods) {
//					String meth = method.getName();
//					// 匹配set方法
//					if (!(meth == null||"".equals(meth)) && "set".equals(meth.substring(0, 3)) && Modifier.isPublic(method.getModifiers())
//							&& ("set" + Character.toUpperCase(attri.charAt(0)) + attri.substring(1)).equals(meth)) {
//						methodMap.put(attri.toLowerCase(), method);
//						break;
//					}
//				}
//			}
//			for(Entry<?, ?> iterator: map.entrySet()){
//				String name = (String) iterator.getKey(); 
//				String value = (String) iterator.getValue();
//				if (value == null){
//					continue;
//				}
//				value = value.trim();
//				name = name.trim();
//
//				Field field = fieldMap.get(name.toLowerCase());
//				if (field == null){
//					continue;
//				}
//				Method method = methodMap.get(name.toLowerCase());
//				if (method == null){
//					continue;
//				}
//				fill(modelBean, field, method, value);
//			}
////			while (it.hasNext()) {
////				String name = (String) it.next();
////				String value = (String) map.get(name);
////
////				if (value == null){
////					continue;
////				}
////				value = value.trim();
////				name = name.trim();
////
////				Field field = fieldMap.get(name.toLowerCase());
////				if (field == null){
////					continue;
////				}
////				Method method = methodMap.get(name.toLowerCase());
////				if (method == null){
////					continue;
////				}
////				fill(modelBean, field, method, value);
////			}
//
//			for (int i = 0; i < fields.length; i++) {
//				Field field = fields[i];
//				String fieldName = field.getName();
//
//				for (int j = 0; j < methods.length; j++) {
//					Method method = methods[j];
//					String methodName = method.getName();
//					while (it.hasNext()) {
//						String key = (String) it.next();
//						String value = (String) map.get(key);
//						if (fieldName.equals(key)) {
//							Method setMethod = classType.getMethod(methodName, new Class[] { field.getType() });
//							setMethod.invoke(modelBean, new Object[] { value });
//						}
//					}
//				}
//
//			}
//		} catch (SecurityException e) {
//			// TODO Auto-generated catch block
//			LOGGER.info(e.getMessage());
//		} catch (IllegalArgumentException e) {
//			// TODO Auto-generated catch block
//			LOGGER.info(e.getMessage());
//		} catch (NoSuchMethodException e) {
//			// TODO Auto-generated catch block
//			LOGGER.info(e.getMessage());
//		} catch (IllegalAccessException e) {
//			// TODO Auto-generated catch block
//			LOGGER.info(e.getMessage());
//		} catch (InvocationTargetException e) {
//			// TODO Auto-generated catch block
//			LOGGER.info(e.getMessage());
//		}
//
//		return modelBean;
//	}

	/**
	 * 
	 * @Description:TODO
	 * @param modelBean
	 * @param field
	 * @param method
	 * @param value
	 * @return
	 * @return T
	 * @exception:
	 * @author:
	 * @time:2014-12-18 上午9:48:35
	 */
	public static <T> T fill(T modelBean, Field field, Method method, String value) {
		if (value == null || "null".equalsIgnoreCase(value)){
			return modelBean;
		}
		try {
			Object[] oo = new Object[1];
			String type = field.getType().getName();
			if ("java.lang.String".equals(type)) {
				oo[0] = value;
			} else if ("java.lang.Integer".equals(type)) {
				if (value.length() > 0){
					oo[0] = Integer.valueOf(value);
				}
			} else if ("java.lang.Float".equals(type)) {
				if (value.length() > 0){
					oo[0] = Float.valueOf(value);
				}
			} else if ("java.lang.Double".equals(type)) {
				if (value.length() > 0){
					oo[0] = Double.valueOf(value);
				}
			} else if ("java.math.BigDecimal".equals(type)) {
				if (value.length() > 0){
					oo[0] = new BigDecimal(value);
				}
				// }else if("java.util.Date".equals(type)){
				// if (value.length() > 0) oo[0] = DateTimeUtil.create(value,
				// "yyyy-mm-dd hh:mi:ss").toDate();
				// }else if("java.sql.Timestamp".equals(type)){
				// if (value.length() > 0) oo[0] = DateTimeUtil.create(value,
				// "yyyy-mm-dd hh:mi:ss").toTimestamp();
			} else if ("java.lang.Boolean".equals(type)) {
				if (value.length() > 0){
					oo[0] = Boolean.valueOf(value);
				}
			} else if ("java.lang.Long".equals(type)) {
				if (value.length() > 0){
					oo[0] = Long.valueOf(value);
				}
			}
			method.invoke(modelBean, oo);

		} catch (Exception e) {
			LOGGER.info(e.getMessage());
		}
		return modelBean;
	}

}
